package com.yaoxun.gateway.subscribe;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.Topic;

import com.yaoxun.gateway.config.GatewayProperties;
import com.yaoxun.gateway.constant.CacheConstant;
import com.yaoxun.gateway.service.RouteDefinitionService;
import com.yaoxun.gateway.util.JsonUtils;
import com.yaoxun.gateway.xo.dto.ChannelMsg;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RouterSubscribe implements MessageListener {

	@Autowired
	private GatewayProperties gatewayProperties;
	
	@Autowired
	private RouteDefinitionService routeDefinitionService;
	
	public Topic getTopic() {
		String channel = String.format(CacheConstant.CHANNEL, gatewayProperties.getNamespace());
		return ChannelTopic.of(channel);
	}
	
	@Override
	public void onMessage(Message message, byte[] pattern) {
		
		String body = new String(message.getBody());
		
		String channel = new String(message.getChannel());
		
		log.info("RouterSubscribe onMessage  channel:{}, body:{}", channel, body);
		
		ChannelMsg channelMsg = JsonUtils.parse(body, ChannelMsg.class);
		
		if(channelMsg.getAction().equals(ChannelMsg.ADD)) {
			routeDefinitionService.add(channelMsg);
			return ;
		}
		
		if(channelMsg.getAction().equals(ChannelMsg.UPDATE)) {
			routeDefinitionService.update(channelMsg);
			return ;
		}
		
		if(channelMsg.getAction().equals(ChannelMsg.DEL)) {
			routeDefinitionService.delete(channelMsg);
			return ;
		}
		
	}

}
